//
//  CustomLookupController.m
//
//  Created by lee jory on 09-10-22.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "CustomLookupController.h"
#import "MServerDAO.h"
#import "MClientAppDelegate.h"
#import "QueryController.h"
#import "EditFormController.h"
#import "MCUIToolkit.h"
#import "CustomFormController.h"

@interface CustomLookupController (Private)
- (void) loadData;
- (Boolean) isMultiSelect;
- (void)initMultiItems:(NSString *)aValue label:(NSString *)aLabel;
- (void)initSingleItem:(NSString *)aValue label:(NSString *)aLabel;
@end

@implementation CustomLookupController
@synthesize layoutName;
@synthesize queryFilter;
@synthesize page;
@synthesize fieldData;
@synthesize valueField;
@synthesize field;
@synthesize datas;
@synthesize fieldName;
@synthesize lookupBackFills;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	
	self.title = [listLayout objectForKey:@"lbl"];
	[self rightBarButton:@"确定" withStyle:UIBarButtonItemStyleDone selector:@selector(selectAction:)];
	
	pageBar = [MCUIToolkit getPageBar:[MCUIToolkit hasQueryField:listLayout] delegate:self];
	[self.clientView addSubview:pageBar];

	// 根据配置显示/隐藏帮助按钮
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter05-03-05.html";

	
	if ([self isMultiSelect]) {
		[self initMultiItems:[self.fieldData objectForKey:@"value"] label:[self.fieldData objectForKey:@"lbl"]];
	}
	else {
		[self initSingleItem:[self.fieldData objectForKey:@"value"] label:[self.fieldData objectForKey:@"lbl"]];
	}
	
	pageBar.frame = CGRectMake(0, self.height-nToolBarHeight, self.width, nToolBarHeight);
	pageBar.autoresizingMask = nMCViewAutoresizingMask;
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	[self didRotateFromInterfaceOrientation:0];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
	[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
	if (listData) {
		[self loadData];
	}
}

- (void)dealloc {
	[pageBar release];
	[layoutName release];
	[queryFilter release];
	[listData release];
	[listLayout release];
	if(lookupCell) {
		[lookupCell removeFromSuperview];
		[lookupCell release];
	}
	[fieldData release];
	[valueField release];
	[field release];	
	[labelBufferArray release];
	[valueBufferArray release];
	[datas release];
	[fieldName release];
	[lookupBackFills release];
    [super dealloc];
}

#pragma mark ---UIToolbar事件---
-(void)goFirst:(id)inSender {
	if (page != 1) {
		page = 1;
		[self getDataFromServer];
	}
}

-(void)goPrevious:(id)inSender {
	if (page > 1) {
		page = page - 1;
		[self getDataFromServer];
	}
}

-(void)goNext:(id)inSender {
	if (page < totalPage) {
		page = page + 1;
		[self getDataFromServer];
	}
}

-(void)goLast:(id)inSender {
	if (page != totalPage) {
		page = totalPage;
		[self getDataFromServer];
	}
}

-(void)gotoPage:(id)inSender {
	UITextField *inputView = (UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1];
	int goPage = [inputView.text intValue];
	if (goPage >= 1 && goPage <= totalPage) {
		page = goPage;
		[self getDataFromServer];
	}
}

-(void)reload:(id)inSender {
	[self getDataFromServer];
}

-(void)search:(id)inSender {

	QueryController *queryController = [[QueryController alloc] initWithStyle:UITableViewStylePlain];
	queryController.listLayout = listLayout;
	queryController.queryFilter = self.queryFilter;
	[self.navigationController pushViewController:queryController animated:YES];
	[queryController release];
}

#pragma mark ---- 数据加载方法 ----
- (void)getDataFromServer {
	[(UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1] resignFirstResponder];
	[[MServerDAO sharedInstance] getCustomListAsync:layoutName
										queryFilter:queryFilter
											   page:[NSString stringWithFormat:@"%d", page]
										otherParams:[[NSMutableDictionary alloc] init]
										   delegate:self];			
}

- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	if (listLayout) {
		[listLayout release];listLayout = nil;
	}
	listLayout = [returnValue retain];
	listData = [[NSMutableDictionary alloc] init];
	
	NSMutableArray *recordList = [NSMutableArray array];
	if ([listLayout objectForKey:@"rl"]) {
		recordList = [listLayout objectForKey:@"rl"];
	}
	[listData setObject:recordList forKey:@"rl"];
	
	NSMutableArray *buttons = [NSMutableArray array];
	if ([listLayout objectForKey:@"btn"]) {
		buttons = [listLayout objectForKey:@"btn"];
	}
	[listData setObject:buttons forKey:@"btn"];
	
	totalPage = 1;
	if ([listLayout objectForKey:@"tp"]) {
		totalPage = [[listLayout objectForKey:@"tp"] intValue];
	}
	if (totalPage == 0) {
		totalPage = 1;
	}
	if ([pageBar.items count] > 5) {
		UITextField *inputView = (UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1];
		inputView.text = @"";
		inputView.placeholder = [NSString stringWithFormat:@"%d", page];
		UILabel *pageLabel = (UILabel *)(UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:2];
		pageLabel.text = [NSString stringWithFormat:@"/%d", totalPage];		
	}
	[self loadData];		
}

- (void)loadData{
	LookupDataGridComponentDataSource *ds = [[LookupDataGridComponentDataSource alloc] init];
	NSMutableArray *titleWidth = [NSMutableArray array];
	NSString *t = [NSString stringWithFormat:@"%d",48];
	[titleWidth addObject:t];
	NSMutableArray *titleLabel = [NSMutableArray array];
	NSMutableArray *fieldTypes = [NSMutableArray array];
	[titleLabel addObject:@"选择"];
	int itemCount = 0;
	NSMutableArray *listFields = [listLayout objectForKey:@"item"];
	for(int i = 0;i < [listFields count];i++) {
		if ([[[listFields objectAtIndex:i] objectForKey:@"v"] boolValue]) {
			itemCount++;
		}
	}
	int j = -1;
	for(int i = 0;i < [listFields count];i++) {
		if ([[[listFields objectAtIndex:i] objectForKey:@"v"] boolValue]) {
			NSString *label = [MCUIToolkit getFieldLabel:[listFields objectAtIndex:i]];
			if ([listData count] > 0) {
				NSMutableDictionary *style = [MCUIToolkit getFieldTextStyle:[[listData objectForKey:@"rl"] objectAtIndex:0] appItem:[listFields objectAtIndex:i]];
				if (style != nil) {
					if ([style objectForKey:@"label_color"]) {
						NSString *label_color = [style objectForKey:@"label_color"];
						label = [NSString stringWithFormat:@"%@:-:%@", label, label_color];
					}
				}
			}
			[titleLabel addObject:label];
			j++;
			int length = MAX([MCUIToolkit getFieldLength:[listFields objectAtIndex:i]]*8.0, 
							 [MCUIToolkit getMaxWidth:[listData objectForKey:@"rl"] withAppItems:[listFields objectAtIndex:i]]);
//			int length = [MCUIToolkit getFieldLength:[listFields objectAtIndex:i]];
//			if (j == 0 || j == 1 ) {
//				length = 34 / 2;
//			}
//			if (itemCount == 1){
//				length = 34;
//			}
//			if (length == 0) {
//				length = 15;
//			}
//			length = length * 8;
			if ([listData count] > 0) {
				NSMutableDictionary *style = [MCUIToolkit getFieldTextStyle:[[listData objectForKey:@"rl"] objectAtIndex:0] appItem:[listFields objectAtIndex:i]];
				if (style != nil) {
					if ([style objectForKey:@"width"]) {
						length = [[style objectForKey:@"width"] intValue];
						length = (self.width-48.0)*length/100.0;
					}
				}
			}			
			NSString *len = [NSString stringWithFormat:@"%d",length];
			[titleWidth addObject:len];
			NSString *fieldType = [MCUIToolkit getFieldType:[listFields objectAtIndex:i]];
			[fieldTypes addObject:fieldType];
		}
	}	
	
	ds.columnWidth = titleWidth;
	ds.titles = titleLabel;
	ds.fieldTypes = fieldTypes;
	
	NSMutableArray *tableValue = [NSMutableArray array];
	NSMutableArray *recordList = [listData objectForKey:@"rl"];
	//填充数据=============
	for (int row = 0; row < [recordList count]; row++) {
		NSMutableDictionary *record = [[listData objectForKey:@"rl"]objectAtIndex:row];
		
		NSMutableArray *rowData = [[NSMutableArray alloc] init];
		[rowData addObject:@""];
		for (int i = 0;i < [listFields count] ; i++) {
			if ([[[listFields objectAtIndex:i] objectForKey:@"v"] boolValue]) {
				NSString *strValue = [MCUIToolkit getFieldTextValue:record appItem:[listFields objectAtIndex:i] selectOption:nil];
				NSMutableDictionary *style = [MCUIToolkit getFieldTextStyle:record appItem:[listFields objectAtIndex:i]];
				if (style != nil) {
					if ([style objectForKey:@"font_color"]) {
						NSString *font_color = [style objectForKey:@"font_color"];
						strValue = [NSString stringWithFormat:@"%@:-:%@", strValue, font_color];
					}
				}
				[rowData addObject:strValue];
			}
		}
		[tableValue addObject:rowData];
		[rowData release];
	}
	ds.data = tableValue;	
	
	if (lookupCell != nil) {
		[lookupCell removeFromSuperview];
		[lookupCell release];
	}

	lookupCell = [[[[MCUserDefaults instance] class:@"LookupCell"] alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height-nToolBarHeight) 
												   data:ds 
									   valueBufferArray:valueBufferArray
									   labelBufferArray:labelBufferArray
											   listData:[listData objectForKey:@"rl"]
										  isMultiSelect:[self isMultiSelect] 
												 record:[NSMutableDictionary dictionary] 
											  totalPage:0
											currentPage:0];
	lookupCell.listData = [listData objectForKey:@"rl"];
	lookupCell.isMultiSelect = [self isMultiSelect];
	[ds release];
	[self.clientView addSubview:lookupCell];
}


//导航栏上动作按钮的点击事件
- (void) selectAction: (id) sender {
	@try {
		NSString *labelString = @"";
		NSString *valueString = @"";
		for(int i = 0; i<[lookupCell.valueBufferArray count]; i++) {
			valueString = [valueString stringByAppendingFormat:@"%@,",[valueBufferArray objectAtIndex:i]];
			labelString = [labelString stringByAppendingFormat:@"%@,",[labelBufferArray objectAtIndex:i]];
		}
		if ([labelString length] > 0) {
			labelString = [labelString substringToIndex:[labelString length] - 1];
			valueString = [valueString substringToIndex:[valueString length] - 1];
		}
		[self.fieldData setObject:valueString forKey:@"value"];
		[self.fieldData setObject:labelString forKey:@"lbl"];
		self.valueField.text = labelString;
		
		NSMutableDictionary *fieldLabelData = [NSMutableDictionary dictionary];
		[fieldLabelData setObject:labelString forKey:@"value"];
		[datas setObject:fieldLabelData forKey:[@"__" stringByAppendingString:fieldName]];
		
		UIViewController *editFormController = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
		if ([editFormController isKindOfClass:[EditFormController class]] || [editFormController isKindOfClass:[CustomFormController class]]) {
			if (lookupBackFills != nil) {
				for(int k = 0; k<[lookupBackFills count]; k++){
					NSMutableDictionary *lookupBackFill = [lookupBackFills objectAtIndex:k];
					NSString *name = [lookupBackFill objectForKey:@"bf"];
					NSMutableDictionary *recordData = [lookupCell.aRecord objectForKey:@"data"];
					if (recordData == nil) {
						recordData = [NSMutableDictionary dictionary];
					}
					NSMutableDictionary *fieldDataLookupBack = [recordData objectForKey:name];
					if(fieldDataLookupBack == nil)
						fieldDataLookupBack = [NSMutableDictionary dictionary];
					if ([editFormController isKindOfClass:[EditFormController class]]) {
						[(EditFormController*)editFormController setLookupBackFillByFieldName: [lookupBackFill objectForKey:@"fld"] fieldDataLookupBack:fieldDataLookupBack];	
					} else if ([editFormController isKindOfClass:[CustomFormController class]]) {
						[(CustomFormController*)editFormController setLookupBackFillByFieldName: [lookupBackFill objectForKey:@"fld"] fieldDataLookupBack:fieldDataLookupBack];
					}
				}
			}
			if ([editFormController isKindOfClass:[EditFormController class]])
				[(EditFormController*)editFormController doCalcAction:((MCTextField*)valueField.control)];
		}
		[self.navigationController popViewControllerAnimated:YES];
	}
	@catch (NSException * e) {
		[[MCErrorManagement instance] doError:@"99" 
								returnMessage:[NSString stringWithFormat:@"main: Caught %@: %@", [e name], [e reason]]];		
	}
}

- (void)initMultiItems:(NSString *)aValue label:(NSString *)aLabel {
	labelBufferArray = [[NSMutableArray alloc] init];
	valueBufferArray = [[NSMutableArray alloc] init];
	if (aValue == nil || [aValue isEqualToString:@""]) {
		return;
	}
	
	NSMutableArray *values = [[NSMutableArray alloc] initWithArray:[aValue componentsSeparatedByString:@","]];
	for(int i = 0; i < [values count];i++) {
		if (i == 0 || i == [values count] - 1) {
			if ([[values objectAtIndex:i] isEqualToString:@""]) {
				continue;
			}
		}
		[valueBufferArray addObject:[values objectAtIndex:i]];
	}
	if (aLabel != nil && ![aLabel isEqualToString:@""]) {
		NSMutableArray *labels = [[NSMutableArray alloc] initWithArray:[aLabel componentsSeparatedByString:@","]];
		for(int i = 0; i < [labels count]; i++) {
			[labelBufferArray addObject:[labels objectAtIndex:i]];
		}	
	}
	int count = [valueBufferArray count] - [labelBufferArray count];
	if (count > 0) {
		for (int i = 0; i < count; i++) {
			NSString *value = [[valueBufferArray objectAtIndex:i] copy];
			[labelBufferArray addObject:value];
		}
	}else if (count < 0) {
		for (int i = -count-1; i >= 0; i--) {
			[labelBufferArray removeObjectAtIndex:i];
		}
	}
}

- (void)initSingleItem:(NSString *)aValue label:(NSString *)aLabel {
	valueBufferArray = [[NSMutableArray alloc] init];
	labelBufferArray = [[NSMutableArray alloc] init];
	if (aValue != nil && ![aValue isEqualToString:@""]) {
		[valueBufferArray addObject:aValue];
		[labelBufferArray addObject:aLabel == nil?@"":aLabel];
	}
}

- (Boolean)isMultiSelect {
	NSString *fieldType = [field objectForKey:@"type"];
	if ([fieldType isEqualToString:@"U"]) {
		return YES;
	}
	return NO;
}


@end
